package cn.skyquant.quant4j.jforex.sdk.indicator;

import com.dukascopy.api.IBar;

import java.util.List;

public final class IndicatorUtils {
    /**
     * 计算ATR
     * @param iBarList
     * @param timePeriod 取atr的个数
     * @return
     */
    public final static double[] atrs(List<IBar> iBarList,int timePeriod){
        if(iBarList==null || iBarList.size()==0 || timePeriod<=0){
            return null;
        }
        IBar bar0 = iBarList.get(0);
        double[] trs = new double[iBarList.size()];//TR
        trs[0] = bar0.getHigh() - bar0.getLow();//第一天的atr=高点减去低点
        //先算tr,再算ATR
        for(int i=1;i<iBarList.size();i++){
            IBar bar = iBarList.get(i);
            IBar bar_l = iBarList.get(i-1);
            double a = bar.getHigh() - bar.getLow();
            double b = bar.getHigh() - bar_l.getClose();
            double c = bar_l.getClose() - bar.getLow();
            double tr = Math.max(a,Math.max(b,c));//
            trs[i] = tr;
        }
        double[] atrs = new double[trs.length];//ATR
        double tr_sum = 0;
        //先计算第一个ATR
        int i=0;
        for(;i<timePeriod-1 && i<trs.length-1;i++){
            tr_sum += trs[i];
        }
        if(i>1){
            atrs[0] = tr_sum/(i-1);
        }
        for(int j=1;j<atrs.length;j++){
            atrs[j] = ((timePeriod-1)*atrs[j-1]+trs[j])/timePeriod;
        }
        return atrs;
    }

    /**
     * 计算ATR
     * @param iBarList
     * @param timePeriod 取atr的个数
     * @return
     */
    public static final double atr(List<IBar> iBarList,int timePeriod){
        double[] atrs = atrs(iBarList,timePeriod);
        return atrs==null?0:atrs[atrs.length-1];
    }
}
